<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          总记录数：{{ total }}条
        </template>
        <template #right>
          <el-button
            v-allow="'import-excel'"
            type="warning"
            @click="$router.push('/import')"
          >导入excel</el-button>

          <el-button
            v-allow="'export-excel'"
            :loading="downloadLoading"
            style="margin:0 0 20px 20px;"
            type="danger"
            @click="handleDownload"
          >
            导出excel
          </el-button>

          <el-button type="primary" @click="addEmployee">新增员工</el-button>
        </template>
      </PageTools>

      <el-card>
        <!-- 表格 -->
        <el-table :data="employeeList" style="width: 100%" border @sort-change="sortChange">
          <el-table-column label="序号" type="index" :index="indexMethod" width="50%" />
          <el-table-column label="姓名" prop="username" width="80%" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <!-- <img style="width: 50px;" :src="scope.row.staffPhoto" alt=""> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" width="80%" />
          <el-table-column label="聘用形式" prop="formOfEmployment" width="80%">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column
            label="入职时间"
            sortable="custom"
            :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
            prop="timeOfEntry"
          />

          <!-- @click="$router.push('/detail?id='+ scope.row.id)" -->
          <!-- @click="$router.push('/detail/'+ scope.row.id)" -->
          <!-- @click="$router.push({ name:'detail', params:{id: scope.row.id}, query:{uid: scope.row.id} })" -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="$router.push('/detail/'+ scope.row.id)"
              >查看</el-link>
              <el-link type="primary" :underline="false" @click="doAssignRole(scope.row.id)">分配角色</el-link>
              <el-link
                type="primary"
                :underline="false"
                @click="deleteEmployee(scope.row)"
              >删除</el-link>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            :current-page="page"
            :page-sizes="[4, 6, 8, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 弹窗 -->
    <el-dialog
      title="新增员工"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      @close="$refs.empRef.resetForm()"
    >
      <empDialog ref="empRef" @closeWindow="closeWindow" />
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog
      v-if="isShowDialog"
      title="分配角色"
      :visible.sync="isShowDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <!-- @close="$refs.empRef.resetForm()" -->
      <!-- <empDialog ref="empRef" @closeWindow="closeWindow" /> -->
      <assignRole :id="id" :is-show-dialog.sync="isShowDialog" />
    </el-dialog>

  </div>
</template>

<script>
import empDialog from './empDialog.vue'
import { getEmployeeList, deleteEmployee } from '@/api/employees'
import employeesENUM from '@/constant/employees.js'
import assignRole from '@/views/employees/assignRole.vue'

console.log('employeesENUM', employeesENUM.hireType)

const map = employeesENUM.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})

console.log('map', map)

export default {
  components: { empDialog, assignRole },
  data() {
    return {
      isShowDialog: false,
      tHeader: [],
      listLoading: true,
      downloadLoading: false,
      employeeList: [], // 角色列表
      page: 1, // 当前页
      size: 4, // 每页条数
      total: 0, // 总条数
      dialogFormVisible: false,
      // 校验规则
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }
        ]
      },
      isEdit: false,
      id: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 渲染员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList({ page: this.page, size: this.size })
        console.log('员工列表', res)
        this.employeeList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        this.$message.error('员工列表加载失败')
        console.log(error)
      }
    },
    // 表格第一列数字
    indexMethod(index) {
      return (this.page - 1) * this.size + 1 + index
    },
    format(id) {
      return map[id] || '未知'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 从第一页开始发请求
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 入职时间监听
    sortChange(e) {
      console.log(e)
    },
    // 点击新增员工按钮
    addEmployee() {
      this.dialogFormVisible = true
    },
    // 删除员工
    deleteEmployee(row) {
      console.log(row)

      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteEmployee(row.id)
        if (this.employeeList.length === 1) {
          this.page <= 0 ? this.page = 0 : this.page--
        }
        this.$message.success('删除成功')
        this.loadEmployeeList()
      })
    },
    // 子传父关闭弹窗并跳转到最后一页
    closeWindow() {
      this.dialogFormVisible = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeeList()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getEmployeeList({ page: this.page, size: this.total })
        const list = res.data.rows
        console.log('list', list)

        const data = this.formatJson(list)
        console.log('data', data)

        const tHeader = this.tHeader
        console.log('tHeader', tHeader)

        excel.export_json_to_excel({
          header: tHeader, // 表头
          data, // 表体
          filename: '员工信息', // 导出文件名
          autoWidth: true, // 自适应宽度
          bookType: 'xlsx' // 导出文件后缀名
        })
        this.downloadLoading = false
      })
    },
    formatJson(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      this.tHeader = Object.values(map)

      return list.map(item => {
        return Object.keys(map).map(el => item[el])
      })
    },
    // 点击分配角色按钮
    doAssignRole(id) {
      this.isShowDialog = true
      this.id = id
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
 margin-bottom: 10px;

 .el-link {
  margin-right: 5px;
 }

 .pagination{
  text-align: center;
  margin-top: 20px;
 }
}
</style>
